package com.yeqing.netty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class Client {

    public static void write() {
        try (SocketChannel socketChannel = SocketChannel.open()) {
            // 建立连接
            socketChannel.connect(new InetSocketAddress(7777));
            final ByteBuffer buffer = ByteBuffer.allocate(32);
            buffer.put("Hello 世界".getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            socketChannel.write(buffer);
        } catch (IOException e) {
            System.out.println("客户端出现异常...");
            e.printStackTrace();
        }
    }

    public static void read() {
        try(SocketChannel socketChannel = SocketChannel.open()) {
            socketChannel.connect(new InetSocketAddress(7777));
            int count = 0;
            while (true) {
                ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
                count += socketChannel.read(buffer);
                System.out.println("读取了" + count + "字节");
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void blockIOClient() {
        try (SocketChannel socketChannel = SocketChannel.open()) {
            // 连接服务器
            socketChannel.connect(new InetSocketAddress(18899));
            Thread.sleep(3000);
            ByteBuffer buffer = ByteBuffer.allocate(32);
            buffer.put("01234567890abcdef3333\n".getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            socketChannel.write(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
//        read();
        blockIOClient();

    }
}
